//
//  MBDUploadGroupViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/3/29.
//

import Foundation

import YYText
import SnapKit
import SwiftyJSON
import Toast_Swift
import LGAlertView
import Dispatch
import Kingfisher

@MainActor public protocol MBDControllerTipsProtocal : NSObjectProtocol {
    func heightOfTips() -> CGFloat
    
    func colorOfTips() -> UIColor
}

@MainActor public protocol MBDTableViewControllerTipsProtocal : MBDControllerTipsProtocal {
    func indexOfTableCell() -> Int
    
    func tipsViewToAddCellContent() -> UIView
}


class MBDUploadGroupViewController: MBDBaseViewController {
    var tableView : UITableView!
    var confirmButton : UIButton!
    var logoPicker : MBDGroupLogoPicker?
    var qrCodePicker : MBDGroupQRCodePicker?

    var viewModel : MBDUploadGroupViewModel!
    var nextVC : UIViewController?
    
    init(viewModel: MBDUploadGroupViewModel!) {
        super.init(nibName: nil, bundle: nil)
        self.viewModel = viewModel
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = self.viewModel.isUpdate ? "更新群信息" : "上传群"
        
        viewModel.groupTypeCellModel.tipsClickedBlock =  {(str) -> Void in
            self.view.makeToast("目前只支持微信，其他类型敬请期待",position: .center )
        }
        
        viewModel.groupNameCellModel.tipsClickedBlock =  {(str) -> Void in
            let tipsVC = MBDUploadTipsViewController()
            tipsVC.title = "设置群名"
            tipsVC.imageNames = ["group_name_01","group_name_02"]
            self.navigationController?.pushViewController(tipsVC, animated: true)
        }
        
        viewModel.groupOwnerTitleCellModel.tipsClickedBlock =  {(str) -> Void in
            let tipsVC = MBDUploadTipsViewController()
            tipsVC.title = "设置群主（或管理员）信息"
            tipsVC.imageNames = ["group_name_01","group_owner_01","group_owner_02"]
            self.navigationController?.pushViewController(tipsVC, animated: true)
        }
        viewModel.groupDescTitleCellModel.tipsClickedBlock =  {(str) -> Void in
            self.view.makeToast("详细的描述有助于大家更好地了解你的群",position: .center )
        }
        

        let rightItem = UIButton(frame: CGRectMake(0, 0, 66, 25))
        rightItem.setTitle("自动填充", for: .normal)
        rightItem.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        rightItem.setTitleColor(UIColor(colorHex: 0x4273d0), for: .normal)
        rightItem.addTarget(self, action: #selector(rightItemPressed), for: .touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItem)
        
        tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(tableView)
        
        tableView.backgroundColor = UIColor(colorHex: 0xF4F4F4)
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none

        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 100
        
        tableView.register(MBUploadTitleCell.self, forCellReuseIdentifier: "MBUploadTitleCell")
        tableView.register(MBUploadTextDetailCell.self, forCellReuseIdentifier: "MBUploadTextDetailCell")
        tableView.register(MBUploadContactsDetailCell.self, forCellReuseIdentifier: "MBUploadContactsDetailCell")
        tableView.register(MBUploadPictureDetailCell.self, forCellReuseIdentifier: "MBUploadPictureDetailCell")
        tableView.register(MBDUploadGroupLogoCell.self, forCellReuseIdentifier: "MBDUploadGroupLogoCell")
        tableView.register(MBDUploadGroupQRCodeCell.self, forCellReuseIdentifier: "MBDUploadGroupQRCodeCell")
        tableView.register(MBDRejectReasonCell.self, forCellReuseIdentifier: "MBDRejectReasonCell")
        
        confirmButton = UIButton()
        confirmButton.layer.cornerRadius = 22
        confirmButton.clipsToBounds = true
        confirmButton.backgroundColor = UIColor(colorHex: 0x4273d0)

        let buttonTitle = self.viewModel.isUpdate ? "确认修改" : "确认上传"
        confirmButton.setTitle(buttonTitle, for: UIControl.State.normal)
        confirmButton.addTarget(self, action: #selector(confirmButtonPressed), for: UIControl.Event.touchUpInside)
        confirmButton.setTitleColor(UIColor.white, for: UIControl.State.normal)
        confirmButton.titleLabel?.font=(UIFont.systemFont(ofSize: 14))
        self.view.addSubview(confirmButton)
        
        tableView.snp.makeConstraints { make in
            make.left.equalTo(self.view)
            make.top.equalTo(self.view)
            make.right.equalTo(self.view)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-55)
        }
        
        confirmButton.snp.makeConstraints { make in
            make.centerX.equalTo(self.view)
            make.width.equalTo(200)
            make.height.equalTo(44)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-4)
        }
        
        self.view.setDynamicBackgroundColor()
        self.tableView.setDynamicBackgroundColor()
        
    }
    
    override func updateColors() {
        self.view.setDynamicBackgroundColor()
        self.tableView.setDynamicBackgroundColor()
        self.tableView.reloadData()
    }
    
    @objc func rightItemPressed(){
        // 设置源为相机
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            //创建图片选择控制器
            let pickerVC = UIImagePickerController()
            pickerVC.delegate = self
            
            // 设置源为相机
            pickerVC.sourceType = UIImagePickerController.SourceType.photoLibrary
            self.present(pickerVC, animated: true, completion: nil)
        } else {
            print("------> ERROR")
        }
    }
    
    @objc func realConfirmButtonPressed() {
        let viewModel : MBDUploadGroupViewModel = self.viewModel
        if viewModel.groupTypeDetailCellModel.isEmpty() {
            self.view.makeToast("请选择群类型",position:.center )
            return
        }
                
        if (viewModel.groupNameDetailCellModel.isEmpty()) {
            self.view.makeToast("请设置群名",position:.center )
            return
        }
        
        if (viewModel.groupOwnerDetailCellModel.isEmpty() ) {
            self.view.makeToast("请设置群主或管理员信息",position:.center )
            return
        }
        
        if (viewModel.groupLogoCellModel.isEmpty() ) {
            self.view.makeToast("请上传群 Logo 图片",position:.center )
            return
        }
        
        if (viewModel.groupDescCellModel.isEmpty() ) {
            self.view.makeToast("请设置群描述信息",position:.center )
            return
        }
        
        if false == MBDUserCenter.shared.userInfoFetched {
            self.showDetailViewController(MBDLoginViewController(), sender: nil)
            return
        }
        
        self.startIndicatorAnimating()
        self.doRequest { result in
            self.stopIndicatorAnimationg()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                // your code here
                if true == result {
                    self.navigationController?.popViewController(animated: true)
                }
            }
            
        }
    }
    
    @objc func confirmButtonPressed() {
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(realConfirmButtonPressed), object: nil)
        self.perform(#selector(realConfirmButtonPressed), with: nil, afterDelay: 0.2)
        
    }
    
    func doRequest(completion : @escaping (_ result:Bool)->()) {
        //请求
        self.startIndicatorAnimating()
//        let groupType = viewModel.groupTypeDetailCellModel.text!
        let groupName = viewModel.groupNameDetailCellModel.text!
        let groupOwner = viewModel.groupOwnerDetailCellModel.text!
        let groupDesc = viewModel.groupDescCellModel.text!
        let logoPath = viewModel.groupLogoCellModel.logoPath!
        let groupCodePath = viewModel.groupQRCodeCellModel.qrCodePath ?? ""
        let praisedGroupCodeURLString = viewModel.groupQRCodeCellModel.praisedQRCode ?? ""
        let params : Dictionary<String, Any>
        if self.viewModel.isUpdate {
            let groupId = self.viewModel.groupDetail!.groupId!
            params = ["groupName":groupName,"groupType":"1","groupManager":groupOwner,"groupDesc":groupDesc,"groupId": groupId,"groupLogo":logoPath,"praisedQrUrl":groupCodePath,"praisedQRURL":praisedGroupCodeURLString]
            
            MBDHttpClient.shared.request("/group/update",method:.put,parameters: params).httpClientResponse { error, response in
                self.stopIndicatorAnimationg()
                if nil != error {
                    self.view.makeToast(error?.localizedDescription,position: .center)
                } else {
                    self.view.makeToast("修改成功！",position: .center )
                    completion(true)
                }
            }
        } else {
            params =  ["groupName":groupName,"groupType":"1","groupManager":groupOwner,"groupDesc":groupDesc,"groupLogo":logoPath,"praisedQrUrl":praisedGroupCodeURLString]
            
            MBDHttpClient.shared.doPostRequest("/group/save",parameters: params).httpClientResponse { error, response in
                self.stopIndicatorAnimationg()
                if nil != error {
                    self.view.makeToast(error?.localizedDescription,position: .center)
                } else {
                    self.view.makeToast("发布成功，审核通过后将在首页展示",position: .center )
                    completion(true)
                }
            }
        }
    }
}

extension MBDUploadGroupViewController : UIImagePickerControllerDelegate {

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//        let image: UIImage!
//        image = info[.originalImage] as? UIImage
//        let groupInfo = self.processImage(image: image)
//        debugPrint(groupInfo)
    }
}

extension MBDUploadGroupViewController : UINavigationControllerDelegate {
    
}

extension MBDUploadGroupViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.cellModels.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellModel = self.viewModel.cellModels[indexPath.row]
        
        if cellModel is MBDRejectReasonCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDRejectReasonCell", for: indexPath)
            cell.selectionStyle = .none
            let realCellModel = (cellModel as! MBDRejectReasonCellModel)
            (cell as! MBDRejectReasonCell).cellModel = cellModel
            return cell
        }
        
        if cellModel is MBDUploadGroupTitleCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBUploadTitleCell", for: indexPath)
            cell.selectionStyle = .none
            let realCellModel = (cellModel as! MBDUploadGroupTitleCellModel)
            (cell as! MBUploadTitleCell).cellModel = cellModel
            return cell
        }
        
        if cellModel is MBDUploadGroupNameDetailCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBUploadTextDetailCell", for: indexPath)
            let realCellModel = (cellModel as! MBDUploadGroupNameDetailCellModel)
            let realCell = (cell as! MBUploadTextDetailCell)
            realCell.cellModel = realCellModel
            (cell as! MBUploadTextDetailCell).accessable = true
            return cell
        }
        
        if cellModel is MBDUploadGroupTypeDetailCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBUploadTextDetailCell", for: indexPath)
            let realCellModel = (cellModel as! MBDUploadGroupTypeDetailCellModel)
            let realCell = cell as! MBUploadTextDetailCell
            realCell.cellModel = realCellModel
            realCell.accessable = true
            return cell
        }
        
        if cellModel is MBDUploadGroupOwnerDetailCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBUploadTextDetailCell", for: indexPath)
            let realCellModel = (cellModel as! MBDUploadGroupOwnerDetailCellModel)
            let realCell = cell as! MBUploadTextDetailCell
            realCell.cellModel = realCellModel
            realCell.accessable = true
            return cell
        }
        
        if cellModel is MBDUploadGroupDescCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBUploadTextDetailCell", for: indexPath)
            let realCellModel = (cellModel as! MBDUploadGroupDescCellModel)
            let realCell = cell as! MBUploadTextDetailCell
            realCell.cellModel = realCellModel
            realCell.accessable = true
            return cell
        }
        
        if cellModel is MBDUploadGroupLogoCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDUploadGroupLogoCell", for: indexPath)
            let realCellModel = (cellModel as! MBDUploadGroupLogoCellModel)
            let realCell = cell as! MBDUploadGroupLogoCell
            realCell.cellModel = realCellModel
            return cell
        }
        
        if cellModel is MBDUploadGroupQRCodeCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDUploadGroupQRCodeCell", for: indexPath)
            let realCellModel = (cellModel as! MBDUploadGroupQRCodeCellModel)
            let realCell = cell as! MBDUploadGroupQRCodeCell
            realCell.cellModel = realCellModel
            return cell
        }
        
        return UITableViewCell()
    }
}


extension MBDUploadGroupViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellModel = self.viewModel.cellModels[indexPath.row]
        
        if cellModel is MBDUploadGroupTitleCellModel {
            return (cellModel as! MBDUploadGroupTitleCellModel).cellHeight()
        }
        
        if cellModel is MBDRejectReasonCellModel {
            return (cellModel as! MBDRejectReasonCellModel).cellHeight
        }
        
        return (cellModel as! MBDUploadGroupBaseCellModel).cellHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let cellModel = self.viewModel.cellModels[indexPath.row]
        
        if cellModel is MBDUploadGroupNameDetailCellModel {
            let realCellModel = cellModel as! MBDUploadGroupBaseCellModel
            let text = realCellModel.isEmpty() ? "" : realCellModel.text!
            let viewModel = MBDModifyInfoViewModel(editType: .textField,placeHolder: text,title: realCellModel.nextVCTitle())
            let viewController = MBDModifyInfoViewController(viewModel: viewModel)
            
            self.nextVC = viewController
            viewController.saveInfoBlock = { (str,type) -> Void in
                (cellModel as! MBDUploadGroupNameDetailCellModel).text = str
                self.tableView.reloadData()
            }
            self.navigationController!.pushViewController(viewController, animated: true)

        } else if cellModel is MBDUploadGroupOwnerDetailCellModel {
            let realCellModel = cellModel as! MBDUploadGroupBaseCellModel
            let text = realCellModel.isEmpty() ? "" : realCellModel.text!

            let viewModel = MBDModifyInfoViewModel(editType: .textField,placeHolder: text,title: realCellModel.nextVCTitle())
            let viewController = MBDModifyInfoViewController(viewModel: viewModel)
            
            self.nextVC = viewController
            viewController.saveInfoBlock = { (str,type) -> Void in
                (cellModel as! MBDUploadGroupOwnerDetailCellModel).text = str
                self.tableView.reloadData()
            }
            self.navigationController!.pushViewController(viewController, animated: true)

        } else if cellModel is MBDUploadGroupTypeDetailCellModel {
                        
            let alert = LGAlertView(title: "群类型", message: nil, style: .actionSheet, buttonTitles: ["微信"], cancelButtonTitle: "取消", destructiveButtonTitle: nil, actionHandler: {alert,index, title in
                (cellModel as! MBDUploadGroupTypeDetailCellModel).text = MBDUploadGroupTypeDetailCellModel.Wechat
                self.tableView.reloadData()

            }, cancelHandler: { alertView in
                
            })
            alert.show()
            
        } else if cellModel is MBDUploadGroupDescCellModel {
            let realCellModel = cellModel as! MBDUploadGroupBaseCellModel
            let text = realCellModel.isEmpty() ? "" : realCellModel.text!

            let viewModel = MBDModifyInfoViewModel(editType: .textView,placeHolder: text,title: realCellModel.nextVCTitle())
            let viewController = MBDModifyInfoViewController(viewModel: viewModel)
            
            self.nextVC = viewController
            viewController.saveInfoBlock = { (str,type) -> Void in
                (cellModel as! MBDUploadGroupDescCellModel).text = str
                self.tableView.reloadData()
            }
            self.navigationController!.pushViewController(viewController, animated: true)
        }
        
        else if cellModel is MBDUploadGroupLogoCellModel {
            let cm = (cellModel as! MBDUploadGroupLogoCellModel)
                        
            self.logoPicker = MBDGroupLogoPicker(hostVC: self)
            self.logoPicker!.compltion = { image,picturePath in
                cm.logo = image
                cm.logoPath = picturePath
                self.tableView.reloadData()
            }
            self.logoPicker!.showPicker()

        }
        
        else if cellModel is MBDUploadGroupQRCodeCellModel {
            self.qrCodePicker = MBDGroupQRCodePicker(hostVC: self)
            self.qrCodePicker!.compltion = { image,picturePath,praisedString in
                (cellModel as! MBDUploadGroupQRCodeCellModel).qrCode = image
                (cellModel as! MBDUploadGroupQRCodeCellModel).qrCodePath = picturePath
                (cellModel as! MBDUploadGroupQRCodeCellModel).praisedQRCode = praisedString
                
                self.tableView.reloadData()
            }
            self.qrCodePicker!.showPicker()

        }
    }
}

